//
//  KABAddAddressVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/12.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABAddAddressVC.h"
#import "GlobalHeader.h"
#import "ApiManager.h"
#import "XDAFNetworking.h"
#import "MBProgressHUD+XDPrompt.h"
#import "KABModel.h"
#import "KABAddAddressTCell.h"
#import "XDPickerCityView.h"

@interface KABAddAddressVC ()<UITableViewDelegate, UITableViewDataSource, KABAddAddressTCellDelegate, XDPickerCityViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;

@property (strong, nonatomic) KABReceiverInfoItem *item;

@end

static NSString *const kReuseCellId = @"KABAddAddressTCell";

@implementation KABAddAddressVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"新增收货地址";
}

- (void)initSubViews {
    self.saveBtn.layer.masksToBounds = YES;
    self.saveBtn.layer.cornerRadius = CGRectGetHeight(self.saveBtn.bounds) / 2.0;
    [self.saveBtn addTarget:self action:@selector(saveBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 45.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABAddAddressTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    [cell configViewWithRecInfoItem:self.item index:indexPath.row];
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 2) {
        [self selectCity];
    }
}

#pragma mark - KABAddAddressTCellDelegate
- (void)kABAddAddressTCell:(KABAddAddressTCell *)cell textFieldDidChanged:(UITextField *)textField {
    
}
- (void)kABAddAddressTCell:(KABAddAddressTCell *)cell textFieldDidEndEditing:(UITextField *)textField {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.row == 0) {
        self.item.receiver_name = textField.text;
    }else if (indexPath.row == 1) {
        self.item.receiver_phone = textField.text;
    }
}
- (void)kABAddAddressTCell:(KABAddAddressTCell *)cell textViewDidChanged:(UITextView *)textView {
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}
- (void)kABAddAddressTCell:(KABAddAddressTCell *)cell textViewDidEndEditing:(UITextView *)textView {
    
    NSString *str = textView.text;
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符
    str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@" "];
    str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
    //str就是去掉的string
    
    self.item.address = str;
}

#pragma mark - XDPickerCityViewDelegate
- (void)xDPickerCityView:(XDPickerCityView *)XDFilterView province:(NSString *)province city:(NSString *)city {
    self.item.province = province;
    self.item.city = city;
    [self.tableView reloadData];
}

#pragma mark - event response
- (void)saveBtnTapped:(UIButton *)btn {
    // 校验参数
    if (!self.item.receiver_name.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入收货人"];
        return;
    }
    if (!self.item.receiver_phone.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入联系方式"];
        return;
    }
    if (!self.item.province.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择地区"];
        return;
    }
    if (!self.item.address.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入详细地址"];
        return;
    }
    
    [self requestAddNewReceiver];
}

- (void)selectCity {
    XDPickerCityView *pickerView = [[XDPickerCityView alloc] init];
    pickerView.delegate = self;
    [pickerView showInView:self.view];
}

#pragma mark - private methods
- (void)backToSuperView {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - network request
- (void)requestAddNewReceiver {
    // 收藏必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"receiver_name" : self.item.receiver_name,
                           @"receiver_phone" : self.item.receiver_phone,
                           @"province" : self.item.province,
                           @"city" : self.item.city,
                           @"district" : @"",
                           @"address" : self.item.address};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiReceiverInfo] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"新增地址返回：%@", responseObject);
        [hud hideAnimated:NO];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] receiverListWithDictionary:responseObject];
            MBProgressHUD *hud = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"保存成功"];
            hud.completionBlock = ^(){
                [self backToSuperView];
            };
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"新增地址失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (KABReceiverInfoItem *)item {
    if (!_item) {
        _item = [[KABReceiverInfoItem alloc] init];
    }
    return _item;
}

@end
